package com.yueshang.neuron.modular.system.controller;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yueshang.common.entity.ResultResponse;
import com.yueshang.common.support.BeanKit;
import com.yueshang.framework.constant.factory.PageFactory;
import com.yueshang.framework.excel.ExcelExport;
import com.yueshang.neuron.common.enums.ResultCodeEnum;
import com.yueshang.neuron.core.factory.ConstantFactory;
import com.yueshang.neuron.core.warpper.UserWarpper;
import com.yueshang.neuron.modular.system.api.IUserService;
import com.yueshang.neuron.modular.system.model.User;
import com.yueshang.neuron.modular.system.vo.req.AddUserReq;
import com.yueshang.neuron.modular.system.vo.res.UserDtailRes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.servlet.http.HttpServletResponse;

/**
 * 用户控制类
 *
 * @auton shililu
 * @data 2018-08-30
 */
@RestController
@RequestMapping("/v1/user")
public class UserController extends ApiController {
    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    @Autowired
    private IUserService userService;


    /**
     * 添加用户
     *
     * @param userReq
     * @return
     */
    @PostMapping
    public ResultResponse addUser(@RequestBody AddUserReq userReq) {
        userService.editUser(userReq);
        return ResultResponse.ok(ResultCodeEnum.OPERATION_SUCCESS.getCode());
    }

    /**
     * 更新用户
     *
     * @param userReq
     * @return
     */
    @PutMapping
    public ResultResponse editUser(@RequestBody AddUserReq userReq) {
        userService.editUser(userReq);
        return ResultResponse.ok(ResultCodeEnum.OPERATION_SUCCESS.getCode());
    }

    /**
     * 删除用户
     *
     * @param id 删除用户的id
     * @return
     */
    @DeleteMapping
    public ResultResponse delUser(Long id) {
        //先删除所有用户关联关系 在插入
        userService.removeById(id);
        return ResultResponse.ok(ResultCodeEnum.OPERATION_SUCCESS.getCode());
    }

    /**
     * 分页获取用户列表
     */
    @GetMapping("/users")
    public Object list(@RequestParam(required = false) String searchCondition,
                       @RequestParam(required = false) Long roleId,
                       @RequestParam(required = false) Long deptId) {
        Page<User> page = new PageFactory<User>().defaultPage();
        logger.info("UserController-getUserPageList--page:{}", page.getPages());
        List<Map<String, Object>> result = userService.selectUsers(page, searchCondition, deptId, roleId);
        page.setRecords((List<User>) new UserWarpper(result).warp());
        return ResultResponse.ok(ResultCodeEnum.GAIN_SUCCESS.getCode(), ResultCodeEnum.GAIN_SUCCESS.getMsg(), page);
    }

    /**
     * 查看信息
     */
    @GetMapping("/{id}")
    public ResultResponse info(@PathVariable("id") String id) {
        sys_user_logger.info("UserController-getUserPageList--info-paramte1r:{}", id);
        User user = userService.getById(id);
        if (user == null) {
            return ResultResponse.ok(ResultCodeEnum.GAIN_SUCCESS_EMPTY.getCode(), ResultCodeEnum.GAIN_SUCCESS_EMPTY.getMsg());
        }
        UserDtailRes userDtailRes = new UserDtailRes();
        BeanKit.copyProperties(user, userDtailRes);

        userDtailRes.setDeptStr(ConstantFactory.me().getDeptNameByUserId(id));
        userDtailRes.setManageDeptStr(ConstantFactory.me().getManageDeptNameByUserId(id));
        userDtailRes.setAssistantStr(ConstantFactory.me().getAssistantNameByUserId(id));

        userDtailRes.setJobStatusName(ConstantFactory.me().getJobStatusName(user.getJobStatus()));
        userDtailRes.setSexName(ConstantFactory.me().getSexName(user.getSex()));
        userDtailRes.setStatusName(ConstantFactory.me().getStatusName(user.getStatus()));


        return ResultResponse.ok().put("data", userDtailRes);
    }

    /**
     * 批量删除用户
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/batchDel")
    public ResultResponse batchDel(@RequestBody List<Long> ids) {
        userService.removeByIds(ids);
        return ResultResponse.ok();
    }

    /**
     * 分页获取用户列表
     */
    @GetMapping("/userAll")
    public ResultResponse queryUserAll(User user) {
        //分页参数封装 --反例：@RequestBody Map<String, Object> params
        return ResultResponse.ok().put("page", userService.list(new QueryWrapper<>(user)));
    }

    /**
     * 列表导出
     *
     * @param user
     * @param response
     * @return
     */
    @GetMapping("/export")
    public void export(User user, HttpServletResponse response) {

        List<User> userList = userService.list(new QueryWrapper<User>());

        ExcelExport ee = new ExcelExport("用户列表");

        String[] header = new String[]{"序号","姓名", "用户名","部门","性别", "手机号码","岗位","职位","负责部门","入职日期"};

        List<Map<String, Object>> list = new ArrayList<>();

        if (userList != null && userList.size() != 0) {
            int i=0;
            for (User userEntity : userList) {
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("no",i);
                map.put("NAME", userEntity.getName());
                map.put("account", userEntity.getAccount());
                map.put("deptName", ConstantFactory.me().getDeptNameByUserId(userEntity.getId()));
                map.put("SEX", userEntity.getSex() == 1 ? "男" : (userEntity.getSex() == 2 ? "女" : "未知"));
                map.put("MOBILE", userEntity.getPhone());
                map.put("roleName", userEntity.getPhone());//todo
                map.put("postionName", userEntity.getPhone());//todo
                map.put("manageDeptName", ConstantFactory.me().getManageDeptNameByUserId(userEntity.getId()));
                map.put("entryDate",  userEntity.getEntryDate());
                list.add(map);
                i++;
            }
        }

        ee.addSheetByMap("用户", list, header);
        ee.export(response);
    }
}
